/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Global Trust Authority is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

use std::future::Future;
use std::pin::Pin;

use common_log::info;
use crate::{
    chain::attestation_chain::{AttestationHandler, AttestationContext},
    error::attestation_error::AttestationError,
};

/// Handler for generating evidence response in the attestation chain
pub struct EvidenceResponseHandler {
    next: Option<Box<dyn AttestationHandler>>,
}

impl EvidenceResponseHandler {
    pub fn new() -> Self {
        Self { next: None }
    }
}

impl AttestationHandler for EvidenceResponseHandler {
    fn handle<'a>(&'a self, context: &'a mut AttestationContext) -> Pin<Box<dyn Future<Output = Result<(), AttestationError>> + Send + 'a>> {
        Box::pin(async move {
            info!("Starting evidence response creation for attester type: {}", context.evidence.attester_type);
            let token_instance = &mut context.token_instance;
        
            // Create evidence response
            let evidence_token_response = token_instance.create_evidence_response(
                context.custom_verify_results.clone(),
                context.raw_evidence.clone(),
                context.custom_evaluate_results.clone(),
            );

            // Store results in context
            context.evidence_token_response = Some(evidence_token_response);
            
            info!("Evidence response creation completed successfully");
            Ok(())
        })
    }
    
    fn set_next(&mut self, next: Box<dyn AttestationHandler>) {
        self.next = Some(next);
    }
    
    fn get_next(&self) -> Option<&dyn AttestationHandler> {
        self.next.as_ref().map(|h| h.as_ref())
    }
    
    fn name(&self) -> &'static str {
        "EvidenceResponse"
    }
}